package com.DHH.Controller.Api;

import com.DHH.Config.Constant;
import com.DHH.Dto.Message;
import com.DHH.Entity.Base.BaseUser;
import com.DHH.Entity.Identity.IdentityImgAddress;
import com.DHH.Mapper.Identity.IdentityImgAddressMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Created by 汪玉东 on 2017/8/8.
 */
@Controller
@RequestMapping("/api/img/")
public class ImgUploadController {
    @Resource
    private IdentityImgAddressMapper identityImgAddressMapper;
    @RequestMapping("upLoad")
    @ResponseBody
    public Message imgUpLoad(HttpServletRequest request, HttpServletResponse response){
       Message message=new Message();
        BaseUser baseUser=(BaseUser)request.getSession().getAttribute(Constant.USER_IDENTIFICATION);
        if(baseUser==null){
            message.setState(false);
            message.setMsg("用户未登录");
            return  message;
        }
       try {

        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                MultipartFile file = multiRequest.getFile(iter.next());
                if(file != null){
                    //取得当前上传文件的文件名称
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                    if(myFileName.trim() !=""){
                        //重命名上传后的文件名
                        String fileName = "demoUpload" + file.getOriginalFilename();
                        //定义上传路径
                            byte[] filByte=file.getBytes();
                            IdentityImgAddress identityImgAddress=new IdentityImgAddress();
                            //"data:"+file.getContentType()+";base64,"
                            identityImgAddress.setImg(jdkBase64Encoder(new BASE64Encoder().encode(filByte)));
                            identityImgAddress.setUserId(baseUser.getId());
                        identityImgAddressMapper.insert(identityImgAddress);
                        if(identityImgAddress.getId()!=null){
                            IdentityImgAddress identityImgAddress2=new IdentityImgAddress();
                            identityImgAddress2.setId(identityImgAddress.getId());
                            message.setState(true);
                            message.setMsg("上传成功");
                            message.setData(identityImgAddress2);
                        }else{
                            message.setState(false);
                            message.setMsg("上传失败");
                        }


                    }
                }

                //记录上传该文件后的时间
                int finaltime = (int) System.currentTimeMillis();
            }

        }
           return  message;
        } catch (Exception e) {
           message.setState(false);
           message.setMsg("上传失败");
           return  message;
        }


    }

    @RequestMapping("/{id}")
    @ResponseBody
    public void show(@PathVariable("id") Integer id,HttpServletResponse response){
        IdentityImgAddress identityImgAddress=new IdentityImgAddress();
        identityImgAddress.setId(id);
        identityImgAddress=identityImgAddressMapper.selectByPrimaryKey(identityImgAddress);
        String base64=jdkBase64Decoder(identityImgAddress.getImg());
        GenerateImage(base64,response);
    }

    private static String jdkBase64Encoder(String str)
    {
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(str.getBytes());
        return encode;
    }

    /**
     * 使用jdk的base64 解密字符串
     * 返回为null表示解密失败
     * */
    private static String jdkBase64Decoder(String str)
    {
        BASE64Decoder decoder = new BASE64Decoder();
        String decode=null;
        try {
            decode = new String( decoder.decodeBuffer(str));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return decode;
    }

    private  boolean GenerateImage(String imgStr,HttpServletResponse response)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }

            OutputStream out=response.getOutputStream();
            out.write(b);
            out.flush();
            out.close();
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
}
